package com.rongshu.view.penpal.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.home.entity.ShareInformation;
import com.rongshu.view.home.widget.ExpandableEditText;
import com.rongshu.view.penpal.adapter.PenpalArticleTypePageAdapter;
import com.rongshu.view.penpal.bean.PenpalMessageResponse;
import com.rongshu.view.penpal.present.PenpalDetailsPresenter;
import com.rongshu.view.penpal.view.PenpalDetailsView;
import com.rongshu.view.submitArticle.activity.SubmitPostActivity;
import com.rongshu.view.submitArticle.view.AppBarStateChangeListener;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.RoundImageView;
import com.rongshu.widget.ShareBottomDialog;
import com.rongshu.widget.TabPageIndicator;
import com.umeng.socialize.UMShareAPI;
import com.utils.DensityUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2018/11/7.
 * description：笔友会详情
 * 接收参数：
 * penpalwill_id 笔友会id
 */
public class PenpalDetailActivity extends BaseActivity<PenpalDetailsPresenter> implements PenpalDetailsView {
    @BindView(R.id.head_content)
    RelativeLayout headContent;
    @BindView(R.id.penpal_logo)
    RoundImageView penpalLogo;
    @BindView(R.id.penpal_name)
    TextView penpalName;
    @BindView(R.id.penpal_member_num)
    TextView penpalMemberNum;
    @BindView(R.id.penpal_member_note)
    TextView penpalMemberNote;
    @BindView(R.id.penpal_member_city)
    TextView penpalMemberCity;
    @BindView(R.id.post_card)
    TextView postCard;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.notice_layout)
    RelativeLayout noticeLayout;
    @BindView(R.id.penpal_setting)
    RelativeLayout penpalSetting;
    @BindView(R.id.notice)
    ExpandableEditText notice;
    @BindView(R.id.head_left)
    RelativeLayout headLeft;
    @BindView(R.id.penpal_title_name)
    TextView penpalTitleName;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.submit_article)
    ImageView submitArticle;
    @BindView(R.id.indicator)
    TabPageIndicator indicator;
    @BindView(R.id.notice_line)
    View noticeLine;
    private int penpalwill_id = 0;
    private PenpalMessageResponse.ResponseBean.ModelBean model;
    private PenpalArticleTypePageAdapter adapter;
    private boolean showInvite;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_penpal_detail;
    }

    @Override
    protected void initView() {
        showInvite = true;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) headContent.getLayoutParams();
        params.topMargin = DensityUtil.getStateBar(this);
        headContent.setLayoutParams(params);
        Intent intent = getIntent();
        penpalwill_id = intent.getIntExtra(Constant.PENPAL_ID, 0);
        initViewPager();
        headLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        appbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    penpalTitleName.setVisibility(View.GONE);
                } else if (state == State.COLLAPSED) {
                    penpalTitleName.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initViewPager() {
        adapter = new PenpalArticleTypePageAdapter(getSupportFragmentManager(), penpalwill_id);
        viewPager.setAdapter(adapter);
        indicator.setViewPager(viewPager);
        indicator.setIndicatorMode(TabPageIndicator.IndicatorMode.MODE_WEIGHT_NOEXPAND_SAME);// 设置模式，一定要先设置模式
        indicator.setTextColor(ContextCompat.getColor(this, R.color.color_2c2c2c));
        indicator.setIndicatorColor(ContextCompat.getColor(this, R.color.color_3CC051));// 设置底部导航线的颜色
        indicator.setTextColorSelected(ContextCompat.getColor(this, R.color.color_3CC051));// 设置tab标题选中的颜色
        indicator.setTextSize((int) getResources().getDimension(R.dimen.dd_dimen_30px));// 设置字体大小
        indicator.setScrollOffset(3);
    }

    @Override
    protected void initData() {
        setPresenter(new PenpalDetailsPresenter(this), this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showInvite = false;
        presenter.getPenpalDetails(penpalwill_id);
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @OnClick({R.id.penpal_logo, R.id.post_card, R.id.search_more, R.id.submit_article, R.id.penpal_setting, R.id.notice_layout})
    public void onViewClicked(View view) {
        if (UserInfoUtils.getUserInfo() == null) {
            LoginUtils.toLogin(this);
            return;
        }
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.penpal_logo:
                intent.setClass(this, PenpalHomeActivity.class);
                intent.putExtra(Constant.PENPAL_ID, penpalwill_id);
                startActivity(intent);
                break;
            case R.id.post_card:
                if (model != null) {
                    if (model.getIsAdd() == 0) {//申请加入
                        presenter.requestAddPenpal(model.getPenpalwill_id());
                    } else {
                        presenter.getShareUrl();
                    }
                }
                break;
            case R.id.search_more:
                intent.setClass(this, SearchActivity.class);
                intent.putExtra(Constant.PENPAL_ID, penpalwill_id);
                startActivity(intent);
                break;
            case R.id.submit_article:
                intent.setClass(this, SubmitPostActivity.class);
                intent.putExtra(Constant.PENPAL_ID, penpalwill_id);
                startActivity(intent);
                break;
            case R.id.penpal_setting:
                if (model != null) {
                    intent.setClass(this, PenpalManagerActivity.class);
                    intent.putExtra("PenpalModel", model);
                    startActivity(intent);
                }
                break;
        }
    }

    private void bindPenpalMsg(PenpalMessageResponse.ResponseBean.ModelBean model) {
        if (model != null) {
            this.model = model;
            penpalName.setText(model.getPenclubname());
            penpalTitleName.setText(model.getPenclubname());
            GlideUtils.loadImageView(this, penpalLogo, model.getImg(),
                    R.drawable.penpal_default_logo, R.drawable.penpal_default_logo);
            penpalMemberNum.setText("成员 " + model.getPersonnelCount());
            penpalMemberNote.setText(" · 主题 " + model.getPostedCount());
            String district = TextUtils.isEmpty(model.getDistrict()) ? "" : model.getDistrict();
            penpalMemberCity.setText(" · 地区 " + district);
            postCard.setText(model.getIsAdd() == 1 ? "邀请" : "入会");
            //发帖按钮
            if (model.getIsAdd() != 0 && UserInfoUtils.getUserInfo() != null) {
                submitArticle.setVisibility(View.VISIBLE);
            } else {
                submitArticle.setVisibility(View.GONE);
            }
            //设置按钮
            if (model.getRank() == 1 || model.getRank() == 2) {
                penpalSetting.setVisibility(View.VISIBLE);
            } else {
                penpalSetting.setVisibility(View.GONE);
            }
            //公告栏
            if (TextUtils.isEmpty(model.getAnnoun())) {
                noticeLayout.setVisibility(View.GONE);
                noticeLine.setVisibility(View.GONE);
            } else {
                noticeLayout.setVisibility(View.VISIBLE);
                noticeLine.setVisibility(View.VISIBLE);
                try {
                    String replaceContent = model.getAnnoun().replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    String decode = URLDecoder.decode(replaceContent, "utf-8");
                    notice.setText(decode);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (showInvite && model.getIsAdd() != 0 && model.getPersonnelCount() <= 1) {
                BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
                builder.setTitle("快去邀请好友加入笔友会吧");
                builder.setRight("去邀请");
                final BanyanDialog dialog = builder.create();
                builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
                    @Override
                    public void leftClickListener() {

                    }

                    @Override
                    public void rightClickListener() {
                        presenter.getShareUrl();
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    @Override
    public void callBackPenpalMsg(PenpalMessageResponse response) {
        if (response != null && response.getResponse() != null && response.getResponse().getModel() != null) {
            PenpalMessageResponse.ResponseBean.ModelBean bean = response.getResponse().getModel();
            bindPenpalMsg(bean);
        }
    }

    @Override
    public void callBackRequsetJoinResult() {
        if (!model.getRatify()) {//判断加的笔友会不需要审核，则请求接口成功后默认加入成为普通会员
            model.setIsAdd(1);
            postCard.setText("邀请");
            submitArticle.setVisibility(View.VISIBLE);
        } else {
            toast("申请提交成功\n正在进⾏审核");
        }
    }

    @Override
    public void callBackShareResponse(ShareInformation response) {
        ShareBottomDialog.Builder builder = new ShareBottomDialog.Builder(this);
        builder.setShareData(response.getResponse());
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }
}
